package com.itsitio.registeradmin.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.itsitio.registeradmin.dto.UserRegistrationDTO;
import com.itsitio.registeradmin.dto.UserRegistrationStatisticDTO;
import com.itsitio.registeradmin.enums.RegistrationStatus;
import com.itsitio.registeradmin.model.Country;
import com.itsitio.registeradmin.model.Portal;
import com.itsitio.registeradmin.model.User;
import com.itsitio.registeradmin.service.CountrySrv;
import com.itsitio.registeradmin.service.PortalSrv;
import com.itsitio.registeradmin.service.UserRegistrationSrv;
import com.itsitio.registeradmin.service.UserSrv;
import com.itsitio.registeradmin.web.UserContext;

@Controller
@SessionAttributes({"userContext"})
public class PortalController extends BaseController{

	private static final Logger log = LoggerFactory.getLogger(PortalController.class);
	 
	@Autowired
	private PortalSrv portalSrv;

	@Autowired
	private CountrySrv countrySrv;

	@Autowired
	private UserRegistrationSrv userRegSrv;
	
	@Autowired
	private UserSrv userSrv;
	
	@RequestMapping("/showUserRegistrationReq.html")
	public String  showUserRegistrationReq(@RequestParam() Integer portalId, @RequestParam() Integer countryId, 
			HttpServletRequest request, Model model){
		
		if(log.isDebugEnabled()) {
			  log.debug("Begin with portalId="+portalId+", countryId="+countryId);
		}

		String filterFromDateString = null;
		String filterToDateString = null;

		  // Get today's date
        Calendar nowDate = Calendar.getInstance();
        Calendar fromDate;
		SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");

        fromDate = (Calendar) nowDate.clone();
        // la busqueda se hace entre los ultimos 90 dias
        fromDate.add(Calendar.DAY_OF_MONTH, - (90));

        filterFromDateString = dateFormatter.format(fromDate.getTime());
        filterToDateString = dateFormatter.format(nowDate.getTime());

		List<UserRegistrationDTO> userRegistrationList = userRegSrv.findUserRegistrationReq(portalId, countryId, fromDate.getTime(), nowDate.getTime(), null, null, null, null ); 
        
		//List<UserRegistration> userRegistrationList= userRegSrv.findUserRegistrationReq(portalId, countryId);		

		//Busco el portal por su ID
		String portalName = "";
		Portal portal = portalSrv.getPortalById(portalId);		
		if (portal != null){
			portalName = portal.getName();
		} else {
			if(log.isWarnEnabled()) {
				  log.warn("No se encontro el portal con el id Id="+portalId);
			}
		}

		//Busco el pais su ID
		String countryName = "";
		Country country = countrySrv.getCountryById(countryId);	
		if (country != null){
			countryName = country.getName();
		} else {
			if(log.isWarnEnabled()) {
				  log.warn("No se encontro el pais con el id Id="+countryId);
			}			
		}
		
		
		
		model.addAttribute("userRegistrationList", userRegistrationList);
		model.addAttribute("portalId", portalId);
		model.addAttribute("portalName", portalName);
		model.addAttribute("countryId", countryId);
		model.addAttribute("countryName", countryName);
		model.addAttribute("userFromDate", filterFromDateString);
		model.addAttribute("userToDate", filterToDateString);
		model.addAttribute("statusList", RegistrationStatus.getStatusListForUserRegistrationFilter());
		
		//setea el breadcrumb
		UserContext userContext = getUserContext(request);
		userContext.setPortalName(portalName);
		userContext.setCountryName(countryName);
		//request.getSession().setAttribute("userContext", userContext);
		
		return forward("showUserRegistrationReq", model);
	}
	
	@RequestMapping("/showPortalStatisticHome.html")
	public String showPortalStatisticHomeController(@RequestParam("userId")Integer userId, 
			HttpServletRequest request, Model model){
		
		if(log.isDebugEnabled()) {
			  log.debug("Begin with userId="+userId);
		}			
		//buscamos el Usuario Administrador
		User userAdmin = userSrv.obtener(userId);

		//setea nombre del Usuario Admin
		UserContext userContext = new UserContext();
		userContext.setUserAdminFirstname(userAdmin.getFirstName());
		userContext.setUserAdminLastname(userAdmin.getLastName());	
		userContext.setUserAdminId(userId);
		request.getSession().setAttribute("userContext", userContext);
		
		List<UserRegistrationStatisticDTO> userRegistrationStatisticList= userRegSrv.findUserRegistrationStatistic(userId);
		
		//List<PortalStatistic> portalStatisticList = portalSrv.findPortalStatistic();
		
		model.addAttribute("userRegistrationStatisticList", userRegistrationStatisticList);
		//model.put("portalStatisticList", portalStatisticList);		
		
		return forward("showPortalStatisticResult", model);
	}
	
	
	@RequestMapping("/filterUserRegistration.html")
	public String filterUserRegistration(Model model, @RequestParam(required=true) Integer portalId, 
			@RequestParam(required=true) Integer countryId,
			@RequestParam(required=true) String userFromDate,
			@RequestParam(required=true) String userToDate,
			@RequestParam(required=false) String userFirstName,
			@RequestParam(required=false) String userLastName,
			@RequestParam(required=false) String userEmail,
			@RequestParam(required=false) String userRegistrationStatus	) {
		
		if(log.isDebugEnabled()) {
			  log.debug("Begin with portalId="+portalId+", countryId="+countryId+", userFromDate="+userFromDate+
					  ", userToDate="+userToDate+" userFirstName="+userFirstName+", userLastName="+userLastName+
					  ", userEmail="+userEmail+", userRegistrationStatus="+userRegistrationStatus);
		}			
		
		SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
		Date filterFromDate = null;
		Date filterToDate = null;
		if (userFromDate!= null && userFromDate.trim().length() > 0){
			try {
				filterFromDate = dateFormatter.parse(userFromDate);
			} catch (ParseException ex) {
				ex.printStackTrace();
			}
		}

		if (userToDate!= null && userToDate.trim().length() > 0){
			try {
				filterToDate = dateFormatter.parse(userToDate);
			} catch (ParseException ex) {
				ex.printStackTrace();
			}
		}

		/*
		System.out.println("===== filterUserRegistration() - filterFromDate="+filterFromDate);
		System.out.println("===== filterUserRegistration() - filterToDate="+filterToDate);
		*/
		
		List<UserRegistrationDTO> userRegistrationList = userRegSrv.findUserRegistrationReq(portalId, countryId, filterFromDate, filterToDate, userFirstName, userLastName, userEmail, userRegistrationStatus );
		
		//Busco el portal por su ID
		String portalName = "";
		Portal portal = portalSrv.getPortalById(portalId);		
		if (portal != null){
			portalName = portal.getName();
		} else {
			if(log.isWarnEnabled()) {
				  log.warn("No se encontro el portal con el id Id="+portalId);
			}
		}

		//Busco el pais su ID
		String countryName = "";
		Country country = countrySrv.getCountryById(countryId);	
		if (country != null){
			countryName = country.getName();
		} else {
			if(log.isWarnEnabled()) {
				  log.warn("No se encontro el pais con el id Id="+countryId);
			}			
		}				
		
		model.addAttribute("userRegistrationList", userRegistrationList);		
		model.addAttribute("portalId", portalId);
		model.addAttribute("portalName", portalName);
		model.addAttribute("countryId", countryId);
		model.addAttribute("countryName", countryName);
		model.addAttribute("userFromDate", userFromDate);
		model.addAttribute("userToDate", userToDate);
		model.addAttribute("userFirstName", userFirstName);
		model.addAttribute("userLastName", userLastName);
		model.addAttribute("userEmail", userEmail);
		model.addAttribute("userRegistrationStatus", userRegistrationStatus);
		model.addAttribute("statusList", RegistrationStatus.getStatusListForUserRegistrationFilter());
		
		return forward( "showUserRegistrationReq", model);		
	}
	
	@RequestMapping("/changeStatus.html")
	public String changeStatus(@RequestParam Integer idUserRegistration, @RequestParam String statusId, 
			@RequestParam String comments, Model model, @RequestParam(required=true) Integer portalId2, 
			@RequestParam(required=true) Integer countryId2,
			@RequestParam(required=true) String userFromDate2,
			@RequestParam(required=true) String userToDate2,
			@RequestParam(required=false) String userFirstName2,
			@RequestParam(required=false) String userLastName2,
			@RequestParam(required=false) String userEmail2,
			@RequestParam(required=false) String userRegistrationStatus2) {
		userRegSrv.changeStatus(idUserRegistration, statusId, comments);
		return filterUserRegistration(model,portalId2,countryId2,userFromDate2,userToDate2,userFirstName2,userLastName2,userEmail2, userRegistrationStatus2);
	}
}
